#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OV7670人脸识别系统 - 主程序
使用face_recognition_core.py中的核心功能
"""

import cv2
import time
from face_recognition_core import FaceRecognitionSystem
from serial_utils import list_serial_ports, select_serial_port, select_baudrate
from utils import *
from config import *

def main():
    """主函数"""
    print_system_info()
    
    # 检查face_recognition库
    if not check_face_recognition_library():
        return
    
    # 获取运行模式
    debug_mode = get_mode_choice()
    
    if not debug_mode:
        # 正常模式：选择串口
        available_ports = list_serial_ports()
        selected_port = select_serial_port(available_ports)
        
        if not selected_port:
            print("\n未能选择有效串口，切换到Debug模式")
            debug_mode = True
        else:
            selected_baudrate = select_baudrate()
    else:
        # Debug模式
        selected_port = DEFAULT_PORT
        selected_baudrate = DEFAULT_BAUDRATE
    
    # 创建人脸识别系统
    print(f"\n正在初始化人脸识别系统...")
    system = FaceRecognitionSystem(
        port=selected_port, 
        baudrate=selected_baudrate,
        debug_mode=debug_mode
    )
    
    try:
        # 加载已知人脸
        system.load_known_faces()
        
        if not debug_mode:
            # 连接串口
            if not system.serial_manager.connect():
                print("串口连接失败")
                return
        
        # 设置显示环境
        setup_display_environment()
        
        # 创建显示窗口
        window_name = 'OV7670 Face Recognition'
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)  # 改为NORMAL模式允许调整大小
        
        # 打印控制说明
        print_control_help(debug_mode)
        
        # 设置系统运行状态
        system.running = True
        
        # 变量初始化
        save_count = 0
        auto_mode = True if debug_mode else True  # Debug模式下默认自动模式
        last_image_time = 0
        
        while system.running:
            frame_start = time.time()
            
            # 获取图像帧
            new_frame_received = False
            if debug_mode:
                # Debug模式：从测试图像加载
                if auto_mode and (time.time() - last_image_time > 3.0):  # 每3秒切换
                    rgb_frame = system.load_next_test_image()
                    last_image_time = time.time()
                    new_frame_received = True
                elif not auto_mode:
                    # 手动模式下等待用户按键切换
                    if 'rgb_frame' not in locals() or rgb_frame is None:
                        rgb_frame = system.load_next_test_image()
                        new_frame_received = True
                else:
                    # 自动模式下，如果还没有图片，加载第一张
                    if 'rgb_frame' not in locals() or rgb_frame is None:
                        rgb_frame = system.load_next_test_image()
                        new_frame_received = True
            else:
                # 正常模式：从串口接收
                rgb_frame = system.receive_frame()
                if rgb_frame is not None:
                    new_frame_received = True
            
            # 始终进行人脸识别（使用最新缓存的图片）
            bgr_frame = system.recognize_faces()
            
            if bgr_frame is not None:
                # 计算缩放后的图像大小
                original_height, original_width = bgr_frame.shape[:2]
                scaled_width = int(original_width * WINDOW_SCALE_FACTOR)
                scaled_height = int(original_height * WINDOW_SCALE_FACTOR)
                
                # 应用最大最小限制
                scaled_width = max(MIN_WINDOW_WIDTH, min(MAX_WINDOW_WIDTH, scaled_width))
                scaled_height = max(MIN_WINDOW_HEIGHT, min(MAX_WINDOW_HEIGHT, scaled_height))
                
                # 直接缩放图像
                scaled_frame = cv2.resize(bgr_frame, (scaled_width, scaled_height), interpolation=cv2.INTER_LINEAR)
                
                # 设置窗口大小并显示缩放后的图像
                cv2.resizeWindow(window_name, scaled_width, scaled_height)
                cv2.imshow(window_name, scaled_frame)
            
            # 检查按键
            key = cv2.waitKey(1) & 0xFF
            
            if key == ord('q') or key == 27:  # 'q'键或ESC键
                print("\n退出程序")
                break
            elif key == ord('s'):  # 保存当前帧
                if bgr_frame is not None:
                    save_count += 1
                    filename = format_filename("saved", save_count)
                    cv2.imwrite(filename, bgr_frame)
                    print(f"图像已保存: {filename}")
                else:
                    print("当前没有可保存的图像")
            elif key == ord('r'):  # 重新加载已知人脸
                print("\n重新加载已知人脸...")
                system.load_known_faces()
            elif key == ord('a') and not debug_mode:  # 切换报警功能
                alarm_status = system.toggle_alarm()
                print(f"报警功能: {'启用' if alarm_status else '禁用'}")
            elif debug_mode and key == ord('n'):  # Debug模式：手动切换到下一张图像
                rgb_frame = system.load_next_test_image()
                last_image_time = time.time()
            elif debug_mode and key == ord(' '):  # Debug模式：切换自动/手动模式
                auto_mode = not auto_mode
                print(f"模式切换: {'自动' if auto_mode else '手动'}")
                if auto_mode:
                    last_image_time = time.time()
    
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"\n程序运行错误: {e}")
    finally:
        # 清理资源
        system.running = False
        if hasattr(system, 'serial_manager'):
            system.serial_manager.disconnect()
        cv2.destroyAllWindows()
        print("程序结束")

if __name__ == "__main__":
    main() 